function array2tree(arr, topId, parentIdKey) {
  const top = [];
  const sub = [];
  const tempObj = {};

  const key = parentIdKey || 'parentId';

  arr.forEach((item) => {
    if (`${item[key]}` === `${topId}`) {
      top.push(item);
    } else {
      sub.push(item);
    }
    item.children = [];
    tempObj[item.id] = item;
  });

  sub.forEach((item) => {
    const parent = tempObj[item[key]] || { children: [] };
    parent.children.push(item);
  });

  sub.forEach(delEmptyChild);
  top.forEach(delEmptyChild);

  function delEmptyChild(item) {
    const { children } = item;
    if (!children.length) {
      delete item.children;
    }
  }

  // console.log('tree--->', tempObj)
  // console.log('tree top--->', top)

  return top;
}

export default array2tree;
